package org.datascooter.parser;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.datascooter.exception.DataScooterException;
import org.datascooter.impl.DataSource;
import org.datascooter.inface.IDataSource;
import org.datascooter.inface.IDataSourceProvider;
import org.datascooter.inface.IXMLReader;
import org.datascooter.utils.DataSourceHandler;

public class DSDataSourceProvider extends AbstractProvider<IDataSource> implements IDataSourceProvider {

	private Map<String, IDataSource> dataSourceMap = new HashMap<String, IDataSource>();
	private IDataSource defaultSource;

	public DSDataSourceProvider(IXMLReader... readerArray) {
		super(readerArray);
	}

	@Override
	public IDataSource getItem(String dname) {
		return dataSourceMap.get(dname);
	}

	@Override
	public IDataSource getDefault() {
		if (defaultSource == null) {
			Logger.getLogger(getClass().getName()).info("**No datatources fould - probably you are not properly initialize datascooter : " + dataSourceMap);
		}
		return defaultSource;
	}

	@Override
	public void putSource(IDataSource dataSource) {
		if (dataSource == null) {
			throw new DataScooterException("***Null datasource");
		}
		dataSourceMap.put(dataSource.getName(), dataSource);
		if (dataSource.isCurrent()) {
			defaultSource = dataSource;
		}
	}

	@Override
	protected void processRoot(IXMLReader element) {
		String isDefault = element.getAttribute("isDefault");
		DataSource dataSource = null;
		if (element.getChildren("connect").length > 0) {
			IXMLReader child = element.getChildren("connect")[0];
			dataSource = new DataSource(child.getAttribute("dname"), child.getAttribute("url"), child.getAttribute("user"), child.getAttribute("password"), Boolean.valueOf(isDefault));
			putSource(dataSource);
		} else {
			IXMLReader[] children = element.getChildren("connectByFile");
			if (children.length > 0) {
				IXMLReader child = children[0];
				try {
					DataSourceHandler handler = new DataSourceHandler(child.resolvePath(child.getAttribute("fileName")));
					List<DataSource> sourceList = handler.getSourceList();
					for (DataSource source : sourceList) {
						putSource(source);
					}
					putSource(handler.getCurrent());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}

	@Override
	public void removeSource(String dname) {
		dataSourceMap.remove(dname);
	}
}
